<template>
  <el-dialog :title="!dataForm.categoryId ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="100px">
      <el-form-item label="分类图片" prop="pic">
        <el-upload class="avatar-uploader" action="http://admin.yami.byesame.com/apis/admin/file/upload/element" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>



      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="dataForm.categoryName"></el-input>
      </el-form-item>
      <el-form-item label="上级分类" prop="parentId">
        <el-cascader expand-trigger="hover" :options="menuList" :props="categoryTreeProps" change-on-select filterable
          v-model="selectedOptions" @change="handleSelectMenuChange">
        </el-cascader>
      </el-form-item>
      <el-form-item label="排序号">
        <el-input-number v-model="dataForm.seq" controls-position="right" @change="handleChange"
          :min="1"></el-input-number>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio v-model="dataForm.status" :label="0">下线</el-radio>
        <el-radio v-model="dataForm.status" :label="1">正常</el-radio>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" size="mini">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" size="mini">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate, idList } from '@/utils'
import { Debounce } from '@/utils/debounce'
import UpLoad from '@/components/pic-upload'
export default {
  components: {
    UpLoad
  },
  data() {
    return {
      picture: '',
      num: 1,
      input: '',
      imageUrl: '',
      visible: false,
      roleList: [],
      dataForm: {
        categoryName: '',
        grade:0,
        parentId: '',
        pic: '',
        seq: 1,    
        status: 1,
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      dataRule: {
        pic: [
          { required: true, message: '分类图片不能为空', trigger: 'blur' },
        ],
        categoryName: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
        ]
      },
      menuList: [],
      categoryTreeProps: {
        value: 'categoryId',
        label: 'categoryName'
      },
      selectedOptions: []
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.dataForm.pic = this.imageUrl
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 计数器
    handleChange(value) {
      console.log(value);
      this.dataForm.seq = value
    },

    init(categoryId) {
      this.dataForm.categoryId = categoryId || 0
      this.$http({
        url: this.$http.adornUrl('/prod/category/listCategory'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.menuList = treeDataTranslate(data, 'categoryId')
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (this.dataForm.categoryId) {
          // 修改
          this.$http({
            url: this.$http.adornUrl(`/prod/category/info/${this.dataForm.categoryId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            console.log(data);
            this.dataForm = data;
            this.selectedMenu = idList(this.menuList, data.parentId, 'menuId', 'children').reverse()
          })
        } else {
          this.selectedMenu = []
        }
      })
    },
    handleSelectMenuChange(val) {
      this.dataForm.parentId = val[val.length - 1]
    },
    // 表单提交
    dataFormSubmit: Debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/prod/category'),
            method: this.dataForm.categoryId ? 'put' : 'post',
            data: this.$http.adornData(this.dataForm)
          }).then(({ data }) => {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
        }
      })
    }),
    handleChange(val) {
      this.dataForm.parentId = val[val.length - 1]
    }
  }

}
</script>

<style scoped>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>